IEEE754Buffer   A
last analyzed

Complexity

Total Complexity 24

Size/Duplication

Total Lines 183
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 24
eloc 76
dl 0
loc 183
rs 10
c 0
b 0
f 0

4 Functions

Rating   Name   Duplication   Size   Complexity  
A constructor 0 37 1
C pack 0 46 11
B packFloatBits_ 0 31 6
B unpack 0 31 6
1
/*
2
 * Copyright (c) 2018-2019 Rafael da Silva Rocha.
3
 * Copyright (c) 2013 DeNA Co., Ltd.
4
 * Copyright (c) 2010, Linden Research, Inc
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining
7
 * a copy of this software and associated documentation files (the
8
 * "Software"), to deal in the Software without restriction, including
9
 * without limitation the rights to use, copy, modify, merge, publish,
10
 * distribute, sublicense, and/or sell copies of the Software, and to
11
 * permit persons to whom the Software is furnished to do so, subject to
12
 * the following conditions:
13
 *
14
 * The above copyright notice and this permission notice shall be
15
 * included in all copies or substantial portions of the Software.
16
 *
17
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24
 *
25
 */
26
27
/**
28
 * @fileoverview Encode and decode IEEE 754 floating point numbers.
29
 * @see https://github.com/rochars/ieee754-buffer
30
 * @see https://bitbucket.org/lindenlab/llsd/raw/7d2646cd3f9b4c806e73aebc4b32bd81e4047fdc/js/typedarray.js
31
 * @see https://github.com/kazuho/ieee754.js/blob/master/ieee754.js
32
 */
33
34
/** 
35
 * @module ieee754-buffer
36
 */
37
38
/**
39
 * A class to encode and decode IEEE 754 floating-point numbers.
40
 */
41
export class IEEE754Buffer {
42
43
  /**
44
   * Pack a IEEE 754 floating point number.
45
   * @param {number} ebits The exponent bits.
46
   * @param {number} fbits The fraction bits.
47
   */
48
  constructor(ebits, fbits) {
49
    /**
50
     * @type {number}
51
     * @private
52
     */
53
    this.ebits = ebits;
54
    /**
55
     * @type {number}
56
     * @private
57
     */
58
    this.fbits = fbits;
59
    /**
60
     * @type {number}
61
     * @private
62
     */
63
    this.bias = (1 << (ebits - 1)) - 1;
64
    /**
65
     * @type {number}
66
     * @private
67
     */
68
    this.numBytes = Math.ceil((ebits + fbits) / 8);
69
    /**
70
     * @type {number}
71
     * @private
72
     */
73
    this.biasP2 = Math.pow(2, this.bias + 1);
74
    /**
75
     * @type {number}
76
     * @private
77
     */
78
    this.ebitsFbits = (ebits + fbits);
79
    /**
80
     * @type {number}
81
     * @private
82
     */
83
    this.fbias = Math.pow(2, -(8 * this.numBytes - 1 - ebits));
84
  }
85
86
  /**
87
   * Pack a IEEE 754 floating point number.
88
   * @param {!Uint8Array|!Array<number>} buffer The buffer.
89
   * @param {number} num The number.
90
   * @param {number} index The index to write on the buffer.
91
   * @return {number} The next index to write on the buffer.
92
   * @throws {TypeError} If input is not a number.
93
   */
94
  pack(buffer, num, index) {
95
    // Only numbers can be packed
96
    if (typeof num != 'number') {
97
      throw new TypeError();
98
    }
99
    // Round overflows
100
    if (Math.abs(num) > this.biasP2 - (this.ebitsFbits * 2)) {
101
      num = num < 0 ? -Infinity : Infinity;
102
    }
103
    /**
104
     * sign, need this to handle negative zero
105
     * @see http://cwestblog.com/2014/02/25/javascript-testing-for-negative-zero/
106
     * @type {number}
107
     */
108
    let sign = (((num = +num) || 1 / num) < 0) ? 1 : num < 0 ? 1 : 0;
109
    num = Math.abs(num);
110
    /** @type {number} */
111
    let exp = Math.min(Math.floor(Math.log(num) / Math.LN2), 1023);
112
    /** @type {number} */
113
    let fraction = roundToEven(num / Math.pow(2, exp) * Math.pow(2, this.fbits));
114
    // NaN
115
    if (num !== num) {
116
      fraction = Math.pow(2, this.fbits - 1);
117
      exp = (1 << this.ebits) - 1;
118
    // Number
119
    } else if (num !== 0) {
120
      if (num >= Math.pow(2, 1 - this.bias)) {
121
        if (fraction / Math.pow(2, this.fbits) >= 2) {
122
          exp = exp + 1;
123
          fraction = 1;
124
        }
125
        // Overflow
126
        if (exp > this.bias) {
127
          exp = (1 << this.ebits) - 1;
128
          fraction = 0;
129
        } else {
130
          exp = exp + this.bias;
131
          fraction = roundToEven(fraction) - Math.pow(2, this.fbits);
132
        }
133
      } else {
134
        fraction = roundToEven(num / Math.pow(2, 1 - this.bias - this.fbits));
135
        exp = 0;
136
      } 
137
    }
138
    return this.packFloatBits_(buffer, index, sign, exp, fraction);
139
  }
140
141
  /**
142
   * Unpack a IEEE 754 floating point number.
143
   * Derived from IEEE754 by DeNA Co., Ltd., MIT License. 
144
   * Adapted to handle NaN. Should port the solution to the original repo.
145
   * @param {!Uint8Array|!Array<number>} buffer The buffer.
146
   * @param {number} index The index to read from the buffer.
147
   * @return {number} The floating point number.
148
   */
149
  unpack(buffer, index) {
150
    /** @type {number} */
151
    let eMax = (1 << this.ebits) - 1;
152
    /** @type {number} */
153
    let significand;
154
    /** @type {string} */
155
    let leftBits = "";
156
    for (let i = this.numBytes - 1; i >= 0 ; i--) {
157
      /** @type {string} */
158
      let t = buffer[i + index].toString(2);
159
      leftBits += "00000000".substring(t.length) + t;
160
    }
161
    /** @type {number} */
162
    let sign = leftBits.charAt(0) == "1" ? -1 : 1;
163
    leftBits = leftBits.substring(1);
164
    /** @type {number} */
165
    let exponent = parseInt(leftBits.substring(0, this.ebits), 2);
166
    leftBits = leftBits.substring(this.ebits);
167
    if (exponent == eMax) {
168
      if (parseInt(leftBits, 2) !== 0) {
169
        return NaN;
170
      }
171
      return sign * Infinity;  
172
    } else if (exponent === 0) {
173
      exponent += 1;
174
      significand = parseInt(leftBits, 2);
175
    } else {
176
      significand = parseInt("1" + leftBits, 2);
177
    }
178
    return sign * significand * this.fbias * Math.pow(2, exponent - this.bias);
179
  }
180
181
  /**
182
   * Pack a IEEE754 from its sign, exponent and fraction bits
183
   * and place it in a byte buffer.
184
   * @param {!Uint8Array|!Array<number>} buffer The byte buffer to write to.
185
   * @param {number} index The buffer index to write.
186
   * @param {number} sign The sign.
187
   * @param {number} exp the exponent.
188
   * @param {number} fraction The fraction.
189
   * @return {number}
190
   * @private
191
   */
192
  packFloatBits_(buffer, index, sign, exp, fraction) {
193
    /** @type {!Array<number>} */
194
    let bits = [];
195
    // the sign
196
    bits.push(sign);
197
    // the exponent
198
    for (let i = this.ebits; i > 0; i -= 1) {
199
      bits[i] = (exp % 2 ? 1 : 0);
200
      exp = Math.floor(exp / 2);
201
    }
202
    // the fraction
203
    let len = bits.length;
204
    for (let i = this.fbits; i > 0; i -= 1) {
205
      bits[len + i] = (fraction % 2 ? 1 : 0);
206
      fraction = Math.floor(fraction / 2);
207
    }
208
    // pack as bytes
209
    /** @type {string} */
210
    let str = bits.join('');
211
    /** @type {number} */
212
    let numBytes = this.numBytes + index - 1;
213
    /** @type {number} */
214
    let k = index;
215
    while (numBytes >= index) {
216
      buffer[numBytes] = parseInt(str.substring(0, 8), 2);
217
      str = str.substring(8);
218
      numBytes--;
219
      k++;
220
    }
221
    return k;
222
  }
223
}
224
225
/**
226
 * Round a number to its nearest even value.
227
 * @param {number} n The number.
228
 * @return {number}
229
 * @private
230
 */
231
function roundToEven(n) {
232
  /** @type {number} */
233
  let w = Math.floor(n);
234
  let f = n - w;
235
  if (f < 0.5) {
236
    return w;
237
  }
238
  if (f > 0.5) {
239
    return w + 1;
240
  }
241
  return w % 2 ? w + 1 : w;
242
}
243